package com.dongdong.service.impl;

import com.dongdong.config.IdWorker;
import com.dongdong.mapper.TbSeckillOrderMapper;
import com.dongdong.model.TbSeckillOrder;
import com.dongdong.result.Result;
import com.dongdong.result.ResultEnums;
import com.dongdong.service.SeckillOrderService;
import com.dongdong.vo.SeckillGoodsVO;
import com.dongdong.vo.UserVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;


@Service
public class SeckillOrderServiceImpl implements SeckillOrderService {

    @Autowired
    private TbSeckillOrderMapper tbSeckillOrderMapper;
    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private SeckillGoodsServiceImpl seckillGoodsService ;

    @Autowired
    private IdWorker idWorker;

    @Override
    public Result submitSeckillorder(Long id, UserVO userVO) {
        //通过秒杀商品id从redis中获取商品信息
        SeckillGoodsVO goodsVO = (SeckillGoodsVO) redisTemplate.boundHashOps("seckillGoodsList").get(id);

        //判断vo是否为null
        if(goodsVO==null){
            return Result.RESPONSE(ResultEnums.SECKILL_END); //秒杀商品已经售空
        }

        //判断结束时间
        long end = goodsVO.getEndTime().getTime();
        long start = new Date().getTime();
        if((end-start)<=0){
            return Result.RESPONSE(ResultEnums.SECKILL_TIME_OUT);//秒杀商品已经结束
        }

        //判断库存
        if(goodsVO.getStockCount()==0){
            return Result.RESPONSE(ResultEnums.SECKILL_GOODS_NUM);//库存不足
        }

        //扣减商品库存         更新数据库当前商品的库存
        goodsVO.setStockCount(goodsVO.getStockCount()-1);
        //放入redis缓存
        redisTemplate.boundHashOps(  "seckillGoodsList") .put(id, goodsVO);
        // 判断redis中的库存数量
        if(goodsVO.getStockCount()==0) {
            // 把数据库中的当前秒杀商品的数据的库存数量置为0
            seckillGoodsService.updateSeckillGoodsNum(goodsVO);
        }

        //生成订单
        TbSeckillOrder order = new TbSeckillOrder();
        order.setId(idWorker.nextId());
        order.setSeckillId(goodsVO.getId());
        order.setMoney(goodsVO.getCostPrice());
        order.setUserId(userVO.getUsername());
        order.setSellerId(goodsVO.getSellerId());
        order.setCreateTime(new Date());
        order.setStatus("1");

        tbSeckillOrderMapper.insertSelective(order);
        return Result.RESPONSE(ResultEnums.SECKILL_ORDER_SUCCESSO); //成功
    }
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
}
